#!/usr/bin/python
# -*- coding: utf-8 -*-

import psycopg2
import sys
import cgi
import json
import db_conf
import time
con = None

try:
    qform = cgi.FieldStorage()
    compound_id_1 = qform.getvalue('compound_id_1')	 
    compound_id_2 = qform.getvalue('compound_id_2')
    reaction_text = qform.getvalue('reaction_text') 
    reaction_text = reaction_text + " " + compound_id_1 + " " + compound_id_2	
    a2a_text = qform.getvalue('atom2atom')
    config = db_conf.getConfig('metabvis.conf')
    con = psycopg2.connect(host=db_conf.getDBHost(config), database=db_conf.getDBName(config), port=db_conf.getDBPort(config), user=db_conf.getUser(config), password=db_conf.getPassword(config)) 
    cur = con.cursor()
    insert_reaction_sql = """INSERT INTO reaction (protein_id, ec_number, reaction_text) VALUES (%s,%s,%s) RETURNING reaction_id"""
    cur.execute(insert_reaction_sql,(None, None, reaction_text))
    reaction_id = str(cur.fetchone()[0])
    #insert into atom_transition (compound_id_1,compound_id_2,atom_id_1,atom_id_2,reaction_reaction_id,element_1,element_2) values (100, 200, 1,2,0,'c','h')
    if (a2a_text != None and len(a2a_text) > 3):
        tokens = a2a_text.split(",")
        for a2a in tokens:
	    if (len(a2a) < 3):
	        continue
	    index = a2a.find(":")
	    element_1 = a2a[0]
	    atom_id_1 = a2a[1:index]
	    element_2 = a2a[index+1]
	    atom_id_2 = a2a[index+2:]
	    insert_transition_sql = """insert into atom_transition (compound_id_1,compound_id_2,atom_id_1,atom_id_2,reaction_reaction_id,element_1,element_2) values (%s,%s,%s,%s,%s,%s,%s)"""
	    cur.execute(insert_transition_sql,(compound_id_1, compound_id_2,atom_id_1,atom_id_2,str(reaction_id),element_1,element_2))		 
    cur.execute("commit")     
    print "Content-type: text/html;charset=utf-8\r\n"
    pa = {}
    pa['_reactionid'] = reaction_id
    print json.dumps(pa)
except psycopg2.DatabaseError, e:
    print 'Update Error %s' % e    
    sys.exit(1)    
finally:
    if con:
        con.close()
